<?php
define('YGZD','员工终端');

class personCenter {
	public function index($params){
		$token=$params->token;
		$token = self::verifyToken($token);
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$personCenter = M("module_person_center");
		$customerUser = M("customer_user");
		Session::switchCustomer($cid);
		$weixinUser = M("user_weixin_info");
		$User = M("user");
		$userName=Session::$user['userName'];
		$userId=Session::$user['userId'];
		$personCenterInfo = $personCenter->where("cId=$cid")->find();
		if($userName){
			$userInfo = $weixinUser->where("openid='$userName'")->field("headimgurl,nickname,fullName,phone")->find();
		}else{
			$openid = $User->where("id='$userId'")->getField('openid');
			if($openid){
				$userInfo = $weixinUser->where("openid='$openid'")->field("headimgurl,nickname,fullName,phone")->find();
			}else{
				$userInfo = $User->where("id='$userId'")->field("fullName as nickname,phone")->find();
				$userInfo['headimgurl'] = '';
			}
		}
		if($personCenterInfo){
			$personCenterInfo['menuJson']=json_decode($personCenterInfo['menuJson'],true);
			$isSaleSource = $customerUser->where(['agent' => 'service', 'phone' => $userInfo['phone']])->count();
			if(!$isSaleSource){
				foreach($personCenterInfo['menuJson'][0] as $key => $value){
					if($value['name'] == YGZD){
						unset($personCenterInfo['menuJson'][0][$key]);
					}
				}

			}
		}

		$result['code']=0;
		$result['msg']='获取用户信息成功';
		$result['personCenterInfo']=$personCenterInfo;
		$result['userInfo']=$userInfo;
		$result['mallHue']=Module::callModule("product",null,"getMallHue",null);
		Output::instance()->module("personCenter","index")->object($result);
	}

	/**
	 * 获取个人中心用户基本信息
	 */
	public function getUserInfo($params){
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$personCenter = M("module_person_center");
		Session::switchCustomer($cid);
		$User = M("user");
		$token = $params->token;
		/** 1.判断token是否有效 */
		$token = self::verifyToken($token);
			/** 2.解密token */
		$tokenArray = self::decryptToken($token);
		if(empty($tokenArray['userId'])){
			$tokenArray['userId'] =  Session::$user["userId"];
		}
			/** 3.查询数据 */
		$userInfo = $User
			->where(['id' => $tokenArray['userId']])
			->field("id,phone as loginName,email,phone,fullName,if((sex= 1), '男', '女') AS sex,rural,town,county,city,province,bankAccount,address")
			->find();

		$personCenterInfo = $personCenter->where("cId=$cid")->field("registerExplainPic")->find();

		$result = [
			'code'  => 0,
			'msg'   => '获取用户信息成功',
			'data'   => $userInfo,
		];
		$result['personCenterInfo']=$personCenterInfo;
		$result['mallHue']=Module::callModule("product",null,"getMallHue",null);
//		}

		Output::instance()->module("personCenter","userInfo")->object($result);
	}

	/**
	 * 个人中心用户设置基础信息
	 * @param $fullName /用户名
	 * @param $phone	/手机号
	 */
	public function saveUserInfo($fullName,$phone){
		$cid = Session::$user["customerId"];
		Session::switchCustomer($cid);
		//$weixinUser = M("user_weixin_info");
		$User = M("user");
		$userName=Session::$user['userName'];
		//$userInfo = $weixinUser->where("openid='$userName'")->find();
		$userInfo = $User->where("userName='$userName'")->find();
		$data['fullName']=$fullName;
		$data['phone']=$phone;
		if($userInfo){
			//$result = $weixinUser->where("openid='$userName'")->save($data);
			$result = $User->where("openid='$userName'")->save($data);
		}else{
			$data['nickname']=$fullName;
			$data['openid']=$userName;
			$data['subscribe_time']=date("Y-m-d H:i:s");
			//$result = $weixinUser->add($data);
			$result = $User->add($data);
		}
		if($result){
			Output::instance()->resultCode();
		}else{
			Output::instance()->resultCode(code_sql_error);
		}
	}
	/**
	 * 登录页面及登录接口
	 * @param $params
	 */
	public function login($params){
		$customerId = Session::$user['customerId'];

		$phone = $params->phone;
		$password =  $params->password;
		Session::switchCustomer($customerId);
		$User = M('user');
		$MallStoreModel = m('module_mall_store');

		if($phone && $password){                //登录
			//查询用户信息
			$where['phone'] = array('eq', $phone);
			$userInfo = $User
				->where($where)
				->field("userName,password,id,phone as loginName,email,phone,fullName,if((sex= 1), '男', '女') AS sex,rural,town,county,city,province,bankAccount,address")
				->find();
			if(empty($userInfo)){
				$Out = [
					'code'  => 201,
					'msg'   => '用户不存在',
					'token'  => ''
				];
				Output::instance()->object($Out);
				exit;
			}

			if (strcasecmp($userInfo['password'], Encryption::password($password)) != 0) {
				$Out = [
					'code'  => 203,
					'msg'   => '密码错误',
					'token'  => ''
				];
				Output::instance()->object($Out);
				exit;
			}
//			self::isMerge($userInfo['userName'],$userInfo['phone']);


			//生成token
			$token = self::createToken($userInfo['id']);
			$userInfo['token'] = $data['token'] = $token;
			$data['expired'] = date("Y-m-d H:i:s",strtotime("+1 month"));
			$result = $User->where($where)->save($data);
			if(is_numeric($result)){
				unset($userInfo['password']);
				unset($userInfo['userName']);
				$Out = [
					'code'  => 0,
					'msg'   => '登录成功',
					'data'	=> $userInfo
				];
				Output::instance()->object($Out);
			}else{
				$Out = [
					'code'  => 203,
					'msg'   => '登录失败',
					'token'  => ''
				];
				Output::instance()->object($Out);
			}
		}else{
			$arr = $MallStoreModel->field('isUserNameLogin,isPhoneLogin')->find();
			$arr['isRegister'] = 0;
			if(!isNativeApp() && !isMicroMessengerUserAgent()){
				$arr['isRegister'] = 1;
			}

			Output::instance()->module('personCenter','login')->object($arr);
			exit;
		}
	}
	/**
	 * token 解密
	 * @param $token  生成的token
	 * @return mixed
	 */
	public static function decryptToken($token){
		$tokenString = base64_decode($token);
		$tokenArray['userId'] = substr($tokenString,14);
		$tokenArray['phone'] = substr($tokenString,0,11);
		return $tokenArray;
	}

	/**
	 * 验证token
	 * @param $token 用户唯一标识
	 */
	public function verifyToken($token){
		$customerId = Session::$user['customerId'];
		$userName=Session::$user['userName'];
		$userId=Session::$user['userId'];
		Session::switchCustomer($customerId);
		$User = M('user');

		/**
		 * 判断商城是否需要验证手机号,需要验证并且用户未验证则需要验证
		 */
		$MallStoreModel = m('module_mall_store');
		if($userName){
			$isVerifyPhone = $MallStoreModel->getField('isVerifyPhone');
			if($isVerifyPhone){
				$map['id'] = array('eq', $userId);
				$isVerifyPhone = $User->where($map)->getField('isVerifyPhone');
				if($isVerifyPhone == 0){
					Output::instance()->resultCode(verify_phone,"请先绑定手机号！");
					exit;
				}
			}
		}


		/**
		 * 判断token是否有效
		 */
		if(!empty($token)){
			$where['token'] = array('eq', $token);
			$where['expired'] = array('egt', date('Y-m-d H:i:s'));
			$userInfo = $User->where($where)->find();
			if (empty($userInfo)) {
				Output::instance()->resultCode(token_expire,"当前未登录或登录已失效,请重新登录！");
				exit;
			}
			//有效则返回token
			return $token;
		}else{
			//微信特殊处理
			if($userName){
				$where['userName'] = array('eq', $userName);
				$userInfo = $User->where($where)->find();
				if($userInfo['token'] && $userInfo['expired']){
					$where['expired'] = array('egt', date('Y-m-d H:i:s'));
					$userInfo = $User->where($where)->find();
					if (!empty($userInfo)) {
						cookie("token", $userInfo['token'], array('expire' => 3600 * 24 * 30, 'path' => '/'));
						return $userInfo['token'];
					}else{
						//生成token
						unset($where['expired']);
						$token = self::createToken($userInfo['id']);
						$data['token'] = $token;
						$data['expired'] = date("Y-m-d H:i:s",strtotime("+1 month"));
						$User->where($where)->save($data);
						cookie("token", $userInfo['token'], array('expire' => 3600 * 24 * 30, 'path' => '/'));
						return $token;
					}
				}else{
					//生成token
					$token = self::createToken($userInfo['id']);
					$userInfo['token'] = $data['token'] = $token;
					$data['expired'] = date("Y-m-d H:i:s",strtotime("+1 month"));
					unset($where['expired']);
					$User->where($where)->save($data);
					cookie("token", $userInfo['token'], array('expire' => 3600 * 24 * 30, 'path' => '/'));
					return $token;
				}
			}
			Output::instance()->resultCode(token_expire,"当前未登录或登录已失效,请重新登录！");
			exit;
		}
	}

	/**
	 * 验证手机号验证码登录
	 * @param $params	参数
	 */
	public function phoneLogin($params){
		/** 1.取出手机号和验证码 */
		$phone = $params->phone;
		$code = $params->code;

		/** 2.判断参数是否为空 */
		if(!$phone && !$code){
			$Out = [
				'code'  => 1,
				'msg'   => '参数不能为空',
				'token'   => '',
			];
			Output::instance()->object($Out);
			exit;
		}



		/** 3.判断验证码是否正确 */
		$customerId = Session::$user['customerId'];
		Session::switchCustomer($customerId);
		$User = M('user');

		/** 4.查询用户信息 */
		$where['phone'] = array('eq', $phone);
		$userInfo = $User
			->where($where)
			->field("userName,phone")
			->find();
		if(empty($userInfo)){
			$Out = [
				'code'  => 204,
				'msg'   => '请获取验证码',
				'token'   => '',
			];
			Output::instance()->object($Out);
			return;
		}

		$result = Module::callModule("phone",null,"verifyPhoneCode",$params);
		if(!$result){
			$Out = [
				'code'  => 202,
				'msg'   => '验证码输入错误',
				'token'   => '',
			];
			Output::instance()->object($Out);
			return;
		}



		/** 5.判断是否可以登录或合并 */
		self::isMerge($userInfo['userName'],$userInfo['phone']);

		/** 6.生成token */
		$where['phone'] = array('eq', $phone);
		$userInfo = $User
			->where($where)
			->field("userName,id,phone as loginName,email,phone,fullName,if((sex= 1), '男', '女') AS sex,rural,town,county,city,province,bankAccount,address")
			->find();
		$token = self::createToken($userInfo['id']);
		$userInfo['token'] = $data['token'] = $token;
		$data['expired'] = date("Y-m-d",strtotime("+1 month"));
		$data['isVerifyPhone'] = 1;
		$User->where($where)->save($data);

		/** 7.返回 */
		unset($userInfo['userName']);
		$Out = [
			'code'  => 0,
			'msg'   => '验证码输入正确',
			'data'   => $userInfo,
		];
		Output::instance()->object($Out);
		return;

	}

	/**
	 * 退出登录
	 */
	public function logout(){
        $customerId = Session::$user['customerId'];
        $userId=Session::$user['userId'];
        Session::switchCustomer($customerId);
        $User = M('user');
        $User->where(['id'=>$userId])->setField('token','');
		setcookie("token",'', array('expire' => 0, 'path' => '/'));
		Output::instance()->resultCode();
	}

	/**
	 * 修改手机号
	 * @param $params
	 */
	public function changePhone($params){
		/** 1.取出手机号和验证码 */
		$newPhone = $params->phone;
		$code = $params->code;
		$token = $params->token;
		$customerId = Session::$user['customerId'];
		$userId = Session::$user['userId'];
		Session::switchCustomer($customerId);
		$User = M('user');
		if($newPhone && $code){
			self::verifyToken($token);
			$customerId = Session::$user['customerId'];
			$userId = Session::$user['userId'];
			Session::switchCustomer($customerId);
			$User = M('user');
			/** 2.判断验证码是否正确 */
			$result = Module::callModule("phone",null,"verifyPhoneCode",$params);

			if(!$result){
				$Out = [
					'code'  => 202,
					'msg'   => '验证码输入错误',
					'token'   => '',
				];
				Output::instance()->object($Out);
				return;
			}

			/** 3.判断验证码是否正确并返回 */
			$where['id'] = array('eq', $userId);
			$result = $User->where($where)->save(['phone' => $newPhone,'isVerifyPhone' => 1]);

			if(is_numeric($result)){
				$Out = [
					'code'  => 0,
					'msg'   => '修改成功',
				];
				Output::instance()->object($Out);
				return;
			}else{
				$Out = [
					'code'  => 1,
					'msg'   => '修改失败',
				];
				Output::instance()->object($Out);
				return;
			}
		}else{
			$phone = $User->where(['id' => $userId])->getField('phone');
			$Out['phone'] = $phone;
			Output::instance()->module('personCenter','changePhone')->object($Out);
		}
	}

	/**
	 * 修改姓名
	 * @param $params
	 */
	public function changeName($params){
		$fullName = $params->fullName;
		$token = $params->token;
		$userId = Session::$user['userId'];
		$customerId = Session::$user['customerId'];
		Session::switchCustomer($customerId);
		$User = M('user');
		if($fullName){
			self::verifyToken($token);
			$result = $User->where(['id' => $userId])->save(['fullName' => $fullName]);
			if(is_numeric($result)){
				$Out = [
					'code'  => 0,
					'msg'   => '修改成功',
				];
				Output::instance()->object($Out);
				return;
			}else{
				$Out = [
					'code'  => 1,
					'msg'   => '修改失败',
				];
				Output::instance()->object($Out);
				return;
			}
		}else{
			$fullName = $User->where(['id' => $userId])->getField('fullName');
			$Out['fullName'] = $fullName;
			Output::instance()->module('personCenter','changeName')->object($Out);
		}
	}

	/**
	 * 修改密码
	 * @param $params
	 */
	public function changePassword($params){
		$password = $params->password;
		$newPassword = $params->newPassword;
		$token = $params->token;
		if($password && $newPassword){
			self::verifyToken($token);

			$customerId = Session::$user['customerId'];
			Session::switchCustomer($customerId);
			$userId = Session::$user['userId'];
			$User = M('user');

			$userInfo = $User->where(['id' => $userId])->find();
			if (strcasecmp($userInfo['password'], Encryption::password($password)) != 0) {
				Output::instance()->resultCode(code_user_wrong_pwd);
				exit;
			}

			$result = $User->where(['id' => $userId])->save(['password' => Encryption::password($newPassword)]);

			if(is_numeric($result)){
				$Out = [
					'code'  => 0,
					'msg'   => '修改成功',
				];
				Output::instance()->object($Out);
				return;
			}else{
				$Out = [
					'code'  => 1,
					'msg'   => '修改失败',
				];
				Output::instance()->object($Out);
				return;
			}
		}else{
			Output::instance()->module('personCenter','changePassword')->object([]);
		}
	}

	/**
	 * 注册页面
	 * @param $params
	 */
	public function register($params){
		$name = $params->name;
		$phone = $params->phone;
		$code = $params->code;
		$password = $params->password;
		if($name && $phone && $code && $password){
			$result = Module::callModule("phone",null,"verifyPhoneCode",$params);
			if(!$result){
				$Out = [
					'code' => 202,
					'msg' => '验证码输入错误',
				];
				Output::instance()->object($Out);
				return;
			}

			$customerId = Session::$user['customerId'];
			Session::switchCustomer($customerId);
			$User = M('user');
			$data['lastTime'] = date("Y-m-d H:i:s");
			$data['status'] = 'subscribe';
			$data['profileUrl'] = DEFAULT_PROFILE_URL;
			$data['fullName'] = $name;
			$data['phone'] = $phone;
			$data['password'] = Encryption::password($password);
			$result = $User->add($data);
			if($result){
				$tokenData['token'] = self::createToken($result);
				$tokenData['expired'] = date("Y-m-d H:i:s",strtotime("+1 month"));
				$User->where(['id' => $result])->save($tokenData);
				cookie("token", $tokenData['token'], array('expire' => 3600 * 24 * 60, 'path' => '/'));
				$Out = [
					'code' => 0,
					'msg' => '注册成功',
					'string' => $tokenData['token']
				];
				Output::instance()->object($Out);
				return;
			}else{
				$Out = [
					'code' => 1,
					'msg' => '注册失败',
					'token' => ''
				];
				Output::instance()->object($Out);
				return;
			}
		}else{
			Output::instance()->module('personCenter','register')->object([]);
		}
	}
	//忘记密码-发送验证码
	public function forgotPassword($params){
		$phone = $params->phone;
		$code = $params->code;
		if($phone && $code) {
			/** 2.判断验证码是否正确 */
			$result = Module::callModule("phone",null,"verifyPhoneCode",$params);
			$redis = new Redis();
			if ($redis->connect(C('REDIS_HOST'), C('REDIS_PORT'), C('REDIS_TIMEOUT')) == TRUE
				&& $redis->auth(C('REDIS_PASSWORD')) == TRUE
				&& $redis->select(C('REDIS_BASE_DB_INDEX')) == TRUE
			){
				$redis->set($phone, md5($code));
				$redis->expire($phone, 60);
			}
			if($result) {
				$Out = [
					'code' => 0,
					'msg' => '验证码输入正确',
					'string' => md5($code)
				];
				Output::instance()->object($Out);
				return;
			}else{
				$Out = [
					'code' => 202,
					'msg' => '验证码输入错误',
					'string' => ''
				];
				Output::instance()->object($Out);
			}
		}else{
			Output::instance()->module('personCenter','forgotPassword')->object([]);
		}
	}
	//验证验证码
	public function verifyPhone($params){
		$phone = $params->phone;
		$type = $params->type;
		$isUser = $params->isUser;
		$module = $params->module;
		if(!empty($module)){
			$params->module = $module;
		}else{
			$params->module ='newPersonCenter';
		}
		$customerId = Session::$user['customerId'];
		Session::switchCustomer($customerId);
		$User = M('user');
		$where['phone'] = array('eq', $phone);
		if($isUser == 1){
			$userId = Session::$user['userId'];
			$where['id'] = array('neq', $userId);
		}
		$userInfo = $User->where($where)->find();
		if(!empty($userInfo)){
			if($type == 1){
				$Out = [
					'code' => 1,
					'msg' => '用户已存在',
				];
				Output::instance()->object($Out);
			}else{
				Module::callModule("phone",null,"sendPhoneCode",$params);
			}
		}else{
			if($type == 1){
                $params->recall = 1;
				Module::callModule("phone",null,"sendPhoneCode",$params);
			}else{
				$Out = [
					'code' => 201,
					'msg' => '用户不存在',
				];
				Output::instance()->object($Out);
			}
		}

	}
	//重置密码
	public function resetPassword($params){
		$password = $params->password;
		$phone = $params->phone;
		$string = $params->string;
		$customerId = Session::$user['customerId'];
		Session::switchCustomer($customerId);
		$User = M('user');
		$result = $User->where(['phone' => $phone])->save(['password' => Encryption::password($password)]);
		$redis = new Redis();
		if ($redis->connect(C('REDIS_HOST'), C('REDIS_PORT'), C('REDIS_TIMEOUT')) == TRUE
			&& $redis->auth(C('REDIS_PASSWORD')) == TRUE
			&& $redis->select(C('REDIS_BASE_DB_INDEX')) == TRUE
		){
			$redisString = $redis->get($phone);
			if($redisString != $string){
				$Out = [
					'code'  => 1,
					'msg'   => '已失效',
				];
				Output::instance()->object($Out);
				return;
			}
		}
			if(is_numeric($result)){
				$Out = [
					'code'  => 0,
					'msg'   => '保存成功',
				];
				Output::instance()->object($Out);
				return;
			}else {
				$Out = [
					'code' => 1,
					'msg' => '保存失败',
				];
				Output::instance()->object($Out);
				return;
			}
	}

	//创建token
	public function createToken($userId){
		$ychar = "0,1,2,3,4,5,6,7,8,9";
		$list = explode(",", $ychar);
		$code = '';
		for ($i = 0; $i < 14; $i++) {
			$randnum = rand(0, 9);
			$code .= $list[$randnum];
		}
		$code .=$userId;
		$token = base64_encode($code);
		return $token;
	}



	/**
	 * 判断用户师傅需要合并
	 * @param string $openId	openid
	 * @param $phone			手机号
	 */

	public function isMerge($openId = '',$phone){
		$User = M('user');
		$userName = Session::$user['userName'];
		if($userName){
			if(empty($openId)){
				$isPhone = $User->where(['userName' => $userName])->getField('phone');
				if($isPhone){
					$Out = [
						'code'  => 1,
						'msg'   => '您的微信已绑定其他账号',
					];
					Output::instance()->object($Out);
					exit;
				}else{
					self::userMerge($userName,$phone);
				}
		   }else{
				if($openId != $userName){
					$Out = [
						'code'  => 1,
						'msg'   => '您的微信已绑定其他账号',
					];
					Output::instance()->object($Out);
					exit;
				}
			}
		}
	}

	/**
	 * 用户合并
	 * $username  微信用户
	 * $phone	 手机号用户
	 */
   public function userMerge($userName,$phone){
	   $customerId = Session::$user['customerId'];
	   Session::switchCustomer(0);
	   $orderModle = M("module_product_order");						//订单
	   $orderDetailModle = M("module_product_order_detail");			//订单详情
	   $couponModle = M("module_user_coupon");						//优惠卷
	   $couponSendModle = M("module_coupon_send");					//优惠卷派送
	   $favoriteModle = M("module_product_favorite");					//收藏
	   $favoriteHistroyModle = M("module_product_favorite_histroy");	//收藏历史
	   $purseModle = M("module_user_purse");							//钱包
	   $purseBillModle = M("module_user_purse_bill");					//充值记录
	   $userMergeModle = M("user_merge");					//充值记录
	   Session::switchCustomer($customerId);

	   $User = M('user');												//用户信息
	   $addressModle = M("user_receiver_address");					//收货地址

	   $wxUserId = $User->where(['userName' => $userName])->getField('id');
	   $phoneUserId = $User->where(['phone' => $phone])->getField('id');
	   $User->startTrans();
	   //手机号
	   $result = $User->where(['id' => $wxUserId])->save(['phone' => $phone, 'isVerifyPhone' => 1]);

	   $data['mergeUserId'] = $mergeUserId = $phoneUserId;
	   $data['userId'] = $userId = $wxUserId;
	   $data['cid'] = $customerId;
	   $userMergeModle->add($data);

//	   cookie("userId_$customerId", null);
	   //删除被合并的用户
	   $userDeleteRes = $User->where(['id' => $mergeUserId])->delete();

	   //订单
	   $orderRes = $orderModle->where(['uId' => $mergeUserId, 'fromCustomerId'=>$customerId])->setField('uId', $userId);	//订单表
	   $orderDetailRes = $orderDetailModle->where(['userId' => $mergeUserId, 'fromCustomerId'=>$customerId])->setField('userId', $userId);	//订单详情表

	   //优惠卷
	   $couponRes = $couponModle->where(['userId' => $mergeUserId, 'cId'=>$customerId])->setField('userId', $userId);		//优惠卷
	   $couponSendRes = $couponSendModle->where(['userId' => $mergeUserId, 'cId'=>$customerId])->setField('userId', $userId);		//优惠卷

		//收藏
	   $favoriteRes = $favoriteModle->where(['uid' => $mergeUserId])->setField('uid', $userId);							//收藏列表
	   $favoriteHistroyRes = $favoriteHistroyModle->where(['uid' => $mergeUserId])->setField('uid', $userId);							//收藏历史

	   //钱包
	   $purseInfo = $purseModle->where(['userId' => $mergeUserId, 'cid' =>$customerId])->field('totalRecharge,balance,totalConsume')->find();  //钱包
	   if($purseInfo){
		   $purseData = array(
			   'totalRecharge'=>array('exp','totalRecharge+'.$purseInfo['totalRecharge']),
			   'balance'=>array('exp','balance+'.$purseInfo['balance']),
			   'totalConsume'=>array('exp','totalConsume+'.$purseInfo['totalConsume']),
		   );
		   $purseDeleteRes = $purseModle->where(['userId' => $mergeUserId, 'cid' =>$customerId])->delete();					//删除被合并的账号
		   $userPurse = $purseModle->where(['userId' => $userId, 'cid' =>$customerId])->find();
		   if(empty($userPurse)){
			   $purseData['cid'] = $customerId;
			   $purseData['userId'] = $userId;
			   $purseData['totalRecharge']=0;
			   $purseData['balance']=0;
			   $purseData['updateTime']=date("Y-m-d H:i:s");
			   $purseModle->add($purseData);
		   }
	   }
	   $purseRes = $purseModle->where(['userId' => $userId, 'cid' =>$customerId])->save($purseData);		//保留账号加金额
	   $purseBillRes = $purseBillModle->where(['userId' => $mergeUserId, 'cid' =>$customerId])->setField('userId', $userId);


	   //收获地址
	   $addressRes = $addressModle->where(['uid' => $mergeUserId])->setField('uid',$userId);					//收货地址

//	  $User->rollback();
	  Log::write('$result'.$result);
	  Log::write('$userDeleteRes'.$userDeleteRes);
	  Log::write('$orderRes'.$orderRes);
	  Log::write('$orderDetailRes'.$orderDetailRes);
	  Log::write('$couponRes'.$couponRes);
	  Log::write('$couponSendRes'.$couponSendRes);
	  Log::write('$favoriteRes'.$favoriteRes);
	  Log::write('$favoriteHistroyRes'.$favoriteHistroyRes);
	  Log::write('$purseDeleteRes'.$purseDeleteRes);
	  Log::write('$purseRes'.$purseRes);
	  Log::write('$purseBillRes'.$purseBillRes);
	  Log::write('$addressRes'.$addressRes);
//
//	   var_dump($result);
//	   var_dump($userDeleteRes);
//	   var_dump($orderRes);
//	   var_dump($orderDetailRes);
//	   var_dump($couponRes);
//	   var_dump($couponSendRes);
//	   var_dump($favoriteRes);
//	   var_dump($favoriteHistroyRes);
//	   var_dump($purseDeleteRes);
//	   var_dump($purseRes);
//	   var_dump($purseBillRes);
//	   var_dump($addressRes);die;

	   if($userDeleteRes &&
		   $result &&
		   is_numeric($orderRes) &&
		   is_numeric($orderDetailRes) &&
		   is_numeric($couponRes) &&
		   is_numeric($couponSendRes) &&
		   is_numeric($favoriteRes) &&
		   is_numeric($favoriteHistroyRes) &&
		  // is_numeric($purseDeleteRes) &&
		  // is_numeric($purseRes) &&
		   is_numeric($purseBillRes) &&
		   is_numeric($addressRes)){
		   $User->commit();
	   }else{
		   $User->rollback();
	   }



   }

	/**
	 * 被锁定人列表
	 * @param $uid				用户id
	 * @param $qid				营销圈id
	 * @param null $search		关键字
	 * @param int $start		开始条数
	 * @param int $limit		每页条数
	 * @param string $tpl		加载模版
	 * @param $register		是否注册
	 */
	public function recommenderUserList($search=null,$start=0,$limit=10,$tpl='index',$register){
		if(empty($tpl)){
			$tpl = 'recommendFrends';
		}

		$customerId = Session::$user['customerId'];
		$uid = Session::$user['userId'];
		Session::switchCustomer(0);
		$mimallModel = M("mimall_user");
		Session::switchCustomer($customerId);

//		$where_friend["mi.qId"] = $qid;
		$where_friend["mi.recommenderId"] = array('eq', $uid);
		$where_friend["mi.cId"] = $customerId;
		$strSql = '';
		//增加好友的注册情况筛选
		if ($register == 'yes'){
			$sql = "mi.uId = mi.miUid";
			$strSql .= $sql;
		}else if ($register == 'no'){
			$sql = "mi.uId <> mi.miUid";
			$strSql .= $sql;
		}

		//增加搜索条件
		if (!empty($search)){
			if (!empty($strSql)){
				$sql = ' AND';
			}else{
				$sql = '';
			}
			$sql .= ' ( us.fullName LIKE  "%' . $search . '%" ) OR (wei.nickname LIKE "%' .  $search . '%") OR ( us.phone LIKE "%' . $search . '%")';
			$strSql .= $sql;
		}
		// 最后拼接SQL
		if (!empty($strSql)) {
			$where_friend['_string'] = $strSql;
		}

		//获取数目
		$friendsCount = $mimallModel->alias("mi")
			->join("wx_quan_user qu on mi.uId = qu.uid and qu.deleted=0")
			->join("wx_".$customerId."_user us on mi.uId = us.id")
			->join("wx_".$customerId."_user_weixin_info wei on mi.uId = wei.userId")
			->join("wx_miu_statistics st on mi.uId = st.uid and st.cid=".$customerId)
			->group('mi.qId,mi.uId')
			->where($where_friend)
			->field("mi.refereeUid as upRefereeUid,mi.miUid,us.fullName,mi.uId as uid,wei.headimgurl as profileUrl,us.status,wei.nickname,mi.createTime,mi.openid")
			->select();
		$friendsCount = count($friendsCount);
		//获取信息
		$friendsInfo = $mimallModel->alias("mi")
			->join("wx_quan_user qu on mi.uId = qu.uid and qu.deleted=0")
			->join("wx_".$customerId."_user us on mi.uId = us.id")
			->join("wx_".$customerId."_user_weixin_info wei on mi.uId = wei.userId")
			->join("wx_miu_statistics st on mi.uId = st.uid and st.cid=".$customerId)
			->where($where_friend)
			->order('mi.createTime desc')
			->field("mi.refereeUid as upRefereeUid,mi.miUid,us.fullName,mi.uId as uid,wei.headimgurl as profileUrl,us.status,wei.nickname,mi.createTime,mi.openid")
			->limit($start,$limit)
			->group('mi.uId')
			->select();
		$result['data'] = $friendsInfo;
		$result['total'] = $friendsCount;

		Output::instance()->module("personCenter",$tpl)->object($result);

	}




}